' PicBasic Pro program to demonstrate conversion to and from BCD.


pinout	VAR	PORTC.6		' Define serial output pin
pinin	VAR	PORTC.7		' Define serial input pin

bcdin	VAR	BYTE		' BCD data in
bcdout	VAR	BYTE		' BCD data out
binhold	VAR	BYTE		' Binary data
addamt	CON 12			' Set value to add



		ADCON1 = 7						' Set ports A and E to digital

loop:			
		SerOut2 pinout,396,["Enter 2-digit decimal number:",10,13]	' Send prompt to user

		SerIn2 pinin,396,[HEX2 bcdin]	' Receive 2 characters as BCD data with the HEX2 modifier

		binhold = ((bcdin & $f0)>>4*10)+(bcdin & $0f)	' Convert bcdin to binary
		

		binhold = binhold + addamt		' Add addamt to binary value
		
		IF binhold>99 Then errmess		' Make sure result is less than 100

		bcdout = ((binhold/10)<<4)+(binhold//10)	' Convert binhold to BCD
		
		' Send data as BCD with the HEX2 modifier
		SerOut2 pinout,396,[HEX2 bcdin, " + ", DEC addamt, " = ", HEX2 bcdout,10,13]


		GoTo loop						' Do it forever
		


errmess:								' Send error message

		SerOut2 pinout,396,[10,13,"ERROR: Result greater than 99",10,13,10,13]
		
		GoTo loop						' Begin again
		
		End
